﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using TradeForm.Print;
using System.Globalization;

namespace TradeForm
{
    public partial class FrmPrint : Form
    {
        private DocumentBase _document;

        private string _defcode;
        public FrmPrint()
        {
            InitializeComponent();
        }

        public FrmPrint(string defcode)
        {
            this._defcode = defcode;
            InitializeComponent();
        }

        public FrmPrint(string defcode, string docType)
        {
            this._defcode = defcode;
            InitializeComponent();

            this.cmbDocType.Text = docType;
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintPreview();
        }

        private void PrintPreview()
        {
            //DocumentBase _document = null;
            _document = null;
            switch (this.cmbDocType.Text)
            {
                case "报关单":
                    _document = new CustomBillDocument(this._defcode, true);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    this.printPreviewControl1.Zoom = 1;
                    break;
                case "发票":
                    _document = new InvoiceDocument(this._defcode, true);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    this.printPreviewControl1.Zoom = 1;
                    break;
                case "形式发票":
                    _document = new ProformaInvoiceDocument(this._defcode, true);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    this.printPreviewControl1.Zoom = 1;
                    break;
                case "合同":
                    _document = new ContractDocument(this._defcode, true);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    this.printPreviewControl1.Zoom = 1;

                    break;
                case "托运单":
                    _document = new ShipmentDocument(this._defcode, true);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    this.printPreviewControl1.Zoom = 1;
                    break;
                case "汇票":
                    _document = new PostalOrderDocument(this._defcode, true);
                    PaperSize psize = new PaperSize("A5", Convert.ToInt32(210 * 100 / 25.4), Convert.ToInt32(148 * 100 / 25.4));
                    _document.DefaultPageSettings.PaperSize = psize;
                    // _document.DefaultPageSettings.Landscape = true;
                    this.printPreviewControl1.Zoom = 1;
                    break;
                case "装箱单":
                    _document = new PackListDocument(this._defcode, true);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    break;
                default:
                    break;
            }

            if (_document != null)
            {
                //_document.ShowPrintPreviewDialog();
                this.printPreviewControl1.Document = _document;
                printPreviewControl1.InvalidatePreview();


            }
        }
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //DocumentBase _document = null;
            _document = null;
            switch (this.cmbDocType.Text)
            {
                case "报关单":
                    _document = new CustomBillDocument(this._defcode, this.chkIsPrintBack.Checked);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    break;
                case "发票":
                    _document = new InvoiceDocument(this._defcode, this.chkIsPrintBack.Checked);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    break;
                case "形式发票":
                    _document = new ProformaInvoiceDocument(this._defcode, this.chkIsPrintBack.Checked);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    break;
                case "合同":
                    _document = new ContractDocument(this._defcode, this.chkIsPrintBack.Checked);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    break;
                case "托运单":
                    _document = new ShipmentDocument(this._defcode, this.chkIsPrintBack.Checked);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    break;
                case "汇票":
                    _document = new PostalOrderDocument(this._defcode, this.chkIsPrintBack.Checked);
                    PaperSize psize = new PaperSize("A5", Convert.ToInt32(210 * 100 / 25.4), Convert.ToInt32(148 * 100 / 25.4));
                    _document.DefaultPageSettings.PaperSize = psize;
                    // _document.DefaultPageSettings.Landscape = true;
                    break;
                case "装箱单":
                    _document = new PackListDocument(this._defcode, this.chkIsPrintBack.Checked);
                    _document.DefaultPageSettings.PaperSize.RawKind = 9;
                    break;
                default:
                    break;
            }

            PrintDialog dialog = new PrintDialog();
            if (_document != null)
            {
                dialog.Document = _document;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    _document.Print();
                }
            }
        }

        private void FrmPrint_Load(object sender, EventArgs e)
        {
            // this.cmbDocType.SelectedIndex = 0;
            if (!string.IsNullOrEmpty(this.cmbDocType.Text))
            {
                PrintPreview();
            }
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            config.FrmPosSettings frm = null;
            //foreach (var item in this.MdiParent.MdiChildren)
            //{
            //    if (typeof(config.FrmPosSettings) == item.GetType())
            //    {
            //        frm = (config.FrmPosSettings)item;
            //        break;
            //    }
            //}
            //if (frm == null)
            //{
            frm = new config.FrmPosSettings();
            // }
            // frm.MdiParent = this.MdiParent;
            frm.ShowDialog();
        }

        private void btnOutExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "*.xls|*.xls";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dlg.FileName))
                {
                    switch (this.cmbDocType.Text)
                    {
                        case "报关单":
                            OutCustoms(dlg.FileName);
                            break;
                        case "发票":
                            OutInvoice(dlg.FileName);
                            break;
                        case "形式发票":
                            break;
                        case "合同":
                            break;
                        case "托运单":
                            break;
                        case "汇票":
                            break;
                        case "装箱单":
                            OutPacking(dlg.FileName);
                            break;
                        default:
                            break;
                    }
                }
            }
        }

        private void OutInvoice(string filename)
        {
            try
            {
                C1.C1Excel.C1XLBook xls = new C1.C1Excel.C1XLBook();
                xls.Load(AppDomain.CurrentDomain.BaseDirectory + @"\Template\Invoice.xls");
                C1.C1Excel.XLSheet sheet = xls.Sheets[0];

                sheet[6, 0].Value = _document.Invoice.Consignee;
                C1.C1Excel.XLStyle style = new C1.C1Excel.XLStyle(xls);
                style.AlignHorz = C1.C1Excel.XLAlignHorzEnum.Left;
                style.AlignVert = C1.C1Excel.XLAlignVertEnum.Top;
                style.WordWrap = true;
                sheet[6, 0].Style = style;
                sheet[6, 6].Value = _document.Invoice.InvoiceNo;
                sheet[8, 6].Value = _document.Invoice.ContractNo;
                CultureInfo culinfo = new CultureInfo("en-US");
                sheet[10, 6].Value = _document.Invoice.InvoiceDate.Value.ToString("MMM dd yyyy", culinfo);
                sheet[13, 1].Value = _document.Invoice.FromPort;
                sheet[13, 5].Value = _document.Invoice.DestPort;
                sheet[15, 1].Value = _document.BillExchange.LCno;
                sheet[15, 5].Value = _document.BillExchange.LCBank;


                sheet[18, 0].Value = _document.Invoice.Mark;
                sheet[18, 0].Style = style;

                sheet[19, 2].Value = _document.GoodsSummery.TotalCount.Value.ToString("###,##0") + "  "
                 + _document.GoodsSummery.TotalCountUnit + " OF " + _document.GoodsSummery.TotalEName;

                decimal totalAmount = 0.0m;
                int iCount = 0;
                foreach (GoodsDetail item in _document.GoodsDetail)
                {
                    iCount++;
                    sheet[19 + iCount, 2].Value = item.GoodsEName + " " + (item.Qty.HasValue ? item.Qty.Value.ToString("##0") : "")
                        + " " + item.QtyUnit + " AT "
                        + (item.UnitPrice.HasValue ? (item.Currency + " " + item.UnitPrice.Value.ToString("F2")) : "");

                    sheet[19 + iCount, 6].Value = item.Amount.HasValue ?
                        (item.Currency + " " + item.Amount.Value.ToString("###,##0.00")) : "";

                    totalAmount += (item.Amount.HasValue ? item.Amount.Value : 0.0m);
                }

                sheet[34, 6].Value = totalAmount;
                xls.Save(filename);
                MessageBox.Show("导出Excel成功。");
            }
            catch (System.IO.IOException ex)
            {
                MessageBox.Show("读写文件失败。请确认模板文件已存在，并且目标文件没有被打开。");
            }
            catch (Exception ex)
            {
                MessageBox.Show("未知错误。" + ex.Message);
            }
        }

        private void OutPacking(string filename)
        {
            try
            {
                C1.C1Excel.C1XLBook xls = new C1.C1Excel.C1XLBook();
                xls.Load(AppDomain.CurrentDomain.BaseDirectory + @"\Template\Packing.xls");
                C1.C1Excel.XLSheet sheet = xls.Sheets[0];

                sheet[6, 0].Value = _document.Invoice.Consignee;
                C1.C1Excel.XLStyle style = new C1.C1Excel.XLStyle(xls);
                style.AlignHorz = C1.C1Excel.XLAlignHorzEnum.Left;
                style.AlignVert = C1.C1Excel.XLAlignVertEnum.Top;
                style.WordWrap = true;
                sheet[6, 0].Style = style;
                sheet[6, 5].Value = _document.Invoice.InvoiceNo;
                sheet[8, 5].Value = _document.Invoice.ContractNo;
                CultureInfo culinfo = new CultureInfo("en-US");
                sheet[10, 5].Value = _document.Invoice.InvoiceDate.Value.ToString("MMM dd yyyy", culinfo);
                sheet[10, 1].Value = _document.BillExchange.LCno;

                int iCount = 0;
                decimal totalQty = 0;
                decimal totalGW = 0.0m;
                decimal totalNW = 0.0m;
                decimal totalCtns = 0.0m;
                string qtyUnit = string.Empty;

                foreach (PackListGoods item in _document.PackListGoods)
                {
                    iCount++;
                    sheet[15 + iCount, 0].Value = item.CaseNo;
                    sheet[15 + iCount, 1].Value = item.Ctns.HasValue ? item.Ctns.Value.ToString("##0") : "";
                    sheet[15 + iCount, 2].Value = item.PkgDesc;
                    sheet[15 + iCount, 4].Value = item.Qty.HasValue ? item.Qty.Value.ToString("##0.00") : "";
                    sheet[15 + iCount, 5].Value = item.GrossWeight.HasValue ? item.GrossWeight.Value.ToString("##0.00") : "";
                    sheet[15 + iCount, 6].Value = item.NetWeight.HasValue ? item.NetWeight.Value.ToString("##0.00") : "";

                    totalGW += (item.GrossWeight.HasValue ? item.GrossWeight.Value : 0.0m);
                    totalNW += (item.NetWeight.HasValue ? item.NetWeight.Value : 0.0m);
                    totalQty += (item.Qty.HasValue ? item.Qty.Value : 0.0m);
                    totalCtns += (item.Ctns.HasValue ? item.Ctns.Value : 0.0m);
                }
                sheet[32, 1].Value = totalCtns.ToString("##0");
                sheet[32, 4].Value = totalQty.ToString("##0.00");
                sheet[32, 5].Value = totalGW.ToString("##0.00");
                sheet[32, 6].Value = totalNW.ToString("##0.00");

                xls.Save(filename);
                MessageBox.Show("导出Excel成功。");
            }
            catch (System.IO.IOException ex)
            {
                MessageBox.Show("读写文件失败。请确认模板文件已存在，并且目标文件没有被打开。");
            }
            catch (Exception ex)
            {
                MessageBox.Show("未知错误。" + ex.Message);
            }
        }

        private void OutCustoms(string filename)
        {
            try
            {
                C1.C1Excel.C1XLBook xls = new C1.C1Excel.C1XLBook();
                xls.Load(AppDomain.CurrentDomain.BaseDirectory + @"\Template\Customs.xls");
                C1.C1Excel.XLSheet sheet = xls.Sheets[0];

                sheet[5, 4].Value = _document.CustomsDeclaration.FromPort;
                //C1.C1Excel.XLStyle style = new C1.C1Excel.XLStyle(xls);
                //style.AlignHorz = C1.C1Excel.XLAlignHorzEnum.Left;
                //style.AlignVert = C1.C1Excel.XLAlignVertEnum.Top;
                //style.WordWrap = true;
                //sheet[6, 0].Style = style;
                sheet[8, 15].Value = _document.CustomsDeclaration.TransportMode;//运输方式
                sheet[10, 18].Value = _document.CustomsDeclaration.TradeKind; //贸易方式
                sheet[10, 32].Value = _document.CustomsDeclaration.Remittanceway; // 结汇方式
                sheet[13, 14].Value = _document.CustomsDeclaration.TradeCountry;
                sheet[13, 21].Value = _document.CustomsDeclaration.DestPort;
                sheet[16, 3].Value = _document.CustomsDeclaration.ApprovalNo; //批准文号

                sheet[16, 13].Value = _document.CustomsDeclaration.TurnoverWay; //成交方式
                sheet[18, 4].Value = _document.CustomsDeclaration.ContractNo; //合同协议号
                sheet[18, 12].Value = _document.CustomsDeclaration.TotalCount.HasValue ?
                    _document.CustomsDeclaration.TotalCount.Value.ToString("F2") : ""; //件数
                sheet[18, 19].Value = _document.CustomsDeclaration.PackType; //包装种类
                sheet[18, 24].Value = _document.CustomsDeclaration.TotalGrossWeight.HasValue ?
                    _document.CustomsDeclaration.TotalGrossWeight.Value.ToString("F2") : ""; //毛重
                sheet[18, 31].Value = _document.CustomsDeclaration.TotalNetWeight.HasValue ?
                    _document.CustomsDeclaration.TotalNetWeight.Value.ToString("F2") : "";//净重
                sheet[25, 4].Value = _document.CustomsDeclaration.Mark; //标记唛头 

                int iCount = 0;
                int i = 0;
           
                string qtyUnit = string.Empty;

                foreach (GoodsDetail item in _document.GoodsDetail)
                {
                    i ++;                    
                    sheet[30 + iCount, 0].Value = i;
                    sheet[30 + iCount, 3].Value = item.HSCode;
                    sheet[30 + iCount, 7].Value = item.GoodsEName;
                    sheet[30 + iCount, 14].Value = item.Qty.HasValue ? (item.Qty.Value.ToString("##0.00") + " " + item.QtyUnit) : "";
                    sheet[30 + iCount, 20].Value = item.UnitPrice.HasValue ? (item.Currency + " " + item.UnitPrice.Value.ToString("##0.00")) : "";
                    sheet[30 + iCount, 27].Value = item.Amount.HasValue ? item.Amount.Value.ToString("##0.00") : "";
                    sheet[30 + iCount, 31].Value = item.Currency;
                    iCount += 2;                   
                }

                xls.Save(filename);
                MessageBox.Show("导出Excel成功。");
            }
            catch (System.IO.IOException ex)
            {
                MessageBox.Show("读写文件失败。请确认模板文件已存在，并且目标文件没有被打开。");
            }
            catch (Exception ex)
            {
                MessageBox.Show("未知错误。" + ex.Message);
            }
        }
    }
}
